package com.tom.utils;

import com.tom.model.Page;
import lombok.experimental.UtilityClass;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@UtilityClass
// @Deprecated
public class PageUtils {


    public static<T> Page<T> getPages(long currentPage, long pageSize, List<T> list) {
        Page<T> page = new Page<>();
        if (CollectionUtils.isEmpty(list)) {
            return page;
        }
        long size = list.size();
        if (pageSize > size) {
            pageSize = size;
        }
        // 求出最大页数，防止currentPage越界
        long maxPage = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;
        if (currentPage > maxPage) {
            currentPage = maxPage;
        }
        // 当前页第一条数据下标
        long curIds = currentPage > 1 ? (currentPage - 1) * pageSize : 0;
        List<T> pageList = new ArrayList<>();
        // 将当前页的数据放进pageList
        for (int i = 0; i < pageSize && curIds + i < size; i++) {
            pageList.add(list.get(Integer.parseInt(String.valueOf(curIds + i))));
        }
        page.setCurrent(currentPage).setSize(pageSize).setTotal(list.size()).setRecords(pageList);
        return page;
    }

    public static<T, R> Page<T> getFromIPage(Page<R> source, Function<R, T> function){
        return getFromIPage(source, source.getRecords().stream().map(function).collect(Collectors.toList()));
    }

    public static <T, R> Page<T> getFromIPage(Page<R> source, List<T> targetRecordList){
        Page<T> res = new Page<>();
        res.setRecords(targetRecordList);
        res.setCurrent(source.getCurrent());
        res.setSize(source.getSize());
        res.setPages(source.getPages());
        res.setTotal(source.getTotal());
        return res;
    }

}
